package com.link.play.fit.ai.utils

import com.link.play.fit.ai.BuildConfig
import com.link.play.fit.ai.GlobalConfig
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
import okhttp3.logging.HttpLoggingInterceptor
import okio.IOException
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

object RetrofitClient {

    // 默认配置
    private const val DEFAULT_TIMEOUT = 60L
    private var retrofit: Retrofit? = null
    private var okHttpClient: OkHttpClient? = null

    // 动态域名配置
    private var baseUrl = GlobalConfig.URL_API

    // 初始化配置
    fun init(baseUrl: String = this.baseUrl) {
        this.baseUrl = baseUrl
        getRetrofit()
    }

    // 获取Retrofit实例
    private fun getRetrofit(): Retrofit {
        if (retrofit == null) {
            synchronized(RetrofitClient::class.java) {
                if (retrofit == null) {
                    retrofit = Retrofit.Builder()
                        .baseUrl(baseUrl)
                        .client(getOkHttpClient())
                        .addConverterFactory(GsonConverterFactory.create())
                        .build()
                }
            }
        }
        return retrofit!!
    }

    // 配置OkHttpClient
    private fun getOkHttpClient(): OkHttpClient {
        if (okHttpClient == null) {
            synchronized(RetrofitClient::class.java) {
                if (okHttpClient == null) {
                    // 日志拦截器
                    val logging = HttpLoggingInterceptor().apply {
                        level = if (BuildConfig.DEBUG) {
                            HttpLoggingInterceptor.Level.BODY
                        } else {
                            HttpLoggingInterceptor.Level.NONE
                        }
                    }

                    // 公共参数拦截器
                    val commonInterceptor = CommonParamsInterceptor()

                    okHttpClient = OkHttpClient.Builder()
                        .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                        .readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                        .writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                        .addInterceptor(logging)
//                        .addInterceptor(commonInterceptor)
                        .addInterceptor(TokenInterceptor())
                        .build()
                }
            }
        }
        return okHttpClient!!
    }

    // 创建API Service
    fun <T> createService(serviceClass: Class<T>): T {
        return getRetrofit().create(serviceClass)
    }

    // 动态修改BaseUrl（适用于多域名场景）
    fun changeBaseUrl(newBaseUrl: String) {
        baseUrl = newBaseUrl
        retrofit = null
        okHttpClient = null
    }

    val apiServer: ApiService by lazy {
        RetrofitClient.createService(ApiService::class.java)
    }
}

// 公共参数拦截器
class CommonParamsInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val originalRequest = chain.request()
        val modifiedUrl = originalRequest.url.newBuilder()
            .addQueryParameter("version", BuildConfig.VERSION_NAME)
            .addQueryParameter("platform", "android")
            .build()

        val newRequest = originalRequest.newBuilder()
            .url(modifiedUrl)
            .build()

        return chain.proceed(newRequest)
    }
}

// Token拦截器
class TokenInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val newRequest = request.newBuilder().apply {
            // 添加Token到Header
//            val token = UserManager.getToken()
            val token = "token"

            if (token.isNotEmpty()) {
                header("Authorization", "Bearer $token")
            }
        }.build()
        return chain.proceed(newRequest)
    }
}

//// 统一错误处理
//sealed class ApiResult<out T> {
//    data class Success<out T>(val data: T) : ApiResult<T>()
//    data class Error(val code: Int, val message: String?) : ApiResult<Nothing>()
//    object NetworkError : ApiResult<Nothing>()
//}

//// 使用示例（协程版本）：
//interface ApiService {
//    @GET("user/info")
//    suspend fun getUserInfo(): Response<UserInfo>
//}

// 封装请求方法
//suspend fun <T> safeApiCall(
//    apiCall: suspend () -> Response<T>
//): ApiResult<T> {
//    return try {
//        val response = apiCall()
//        if (response.isSuccessful) {
//            ApiResult.Success(response.body()!!)
//        } else {
//            ApiResult.Error(response.code(), response.message())
//        }
//    } catch (e: IOException) {
//        ApiResult.NetworkError
//    } catch (e: Exception) {
//        ApiResult.Error(-1, e.message)
//    }
//}

// 使用示例
val apiService = RetrofitClient.createService(ApiService::class.java)

//viewModelScope.launch {
//    when (val result = safeApiCall { apiService.getUserInfo() }) {
//        is ApiResult.Success -> {
//            // 处理成功逻辑
//        }
//        is ApiResult.Error -> {
//            // 处理错误
//        }
//        is ApiResult.NetworkError -> {
//            // 处理网络错误
//        }
//    }
//}